package com.moji.controller;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class XMLAppendExample {
    public static void main(String[] args) {
        try {
            // 加载和解析XML文件
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse("src\\main\\resources\\sitemap.xml");

            // 获取根元素
            Element root = document.getDocumentElement().getOwnerDocument().getDocumentElement();

            // 创建一个新的book元素
            Element newBook = document.createElement("book");

            // 为新的book元素添加子元素
            Element title = document.createElement("title");
            title.setTextContent("Effective Java");
            newBook.appendChild(title);

            Element author = document.createElement("author");
            author.setTextContent("Joshua Bloch");
            newBook.appendChild(author);

            // 将新的book元素追加到根元素下
            root.appendChild(newBook);

            // 写入新的XML到文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new java.io.File("src\\main\\resources\\sitemap.xml"));

            transformer.transform(source, result);

            System.out.println("XML file updated successfully.");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
